package com.geek.novel.activity.auth

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.os.Message
import android.view.View
import com.geek.novel.R
import com.geek.novel.activity.base.TitleBarActivity
import com.geek.novel.bo.AppContext
import com.geek.novel.common.Constant
import com.geek.novel.dialog.ConfirmDialog
import com.geek.novel.entity.SysFile
import com.geek.novel.entity.SysUser
import com.geek.novel.listener.ApiResultListener
import com.geek.novel.services.ImageService
import com.geek.novel.services.manager.AuthManager
import com.geek.novel.utils.*
import com.geek.novel.vo.ApiResult
import kotlinx.android.synthetic.main.activity_user_info.*

/**
 * 个人信息页面
 */
class UserInfoActivity: TitleBarActivity(), ApiResultListener {

	//用户信息管理器
	private lateinit var authManager: AuthManager

	//图片的服务类
	private lateinit var imageService: ImageService

	/**确认框*/
	private lateinit var confirmDialog: ConfirmDialog

	override fun pageName(): String{
		return AppContext.getContext().getString(R.string.title_bar_user_info)
	}
	
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_user_info)

		//显示标题栏右侧按钮
		super.showTitleBtn("保存")

		//初始化确认弹框
		this.initConfirmDialog()

		//初始化用户信息管理器
		authManager = AuthManager()
		authManager.setOnApiResultListener(this)

		//图片服务
		imageService = ImageService(this)

		//初始化用户信息
		this.initUserInfo()
	}

	/**标题右侧按钮的点击事件*/
	override fun onTitleBtnClick(view: View) {
		this.saveUserInfo()
	}

	/**附加控件*/
	override fun attachViewChild() {
		layout_userinfo_pic.setOnClickListener(this)
		layout_userinfo_modify_pwd.setOnClickListener(this)
		layout_userinfo_logout.setOnClickListener(this)
	}

	/**初始化确认弹框*/
	private fun initConfirmDialog(){
		confirmDialog = ConfirmDialog(this)
		confirmDialog.setOnConfirmListener("退出登录") {
			SecurityUtil.logout()
			ToastUtils.toast("您已退出登录！")
			finish()
		}
	}

	/**
	 * 点击事件
	 */
	override fun clickEvent(id: Int, v: View) {
		when(id){
			//更换头像
			R.id.layout_userinfo_pic->{
				imageService.showChooseImageDialog()
			}
			//修改密码
			R.id.layout_userinfo_modify_pwd->{
				startActivityByAnim(this, ModifyPasswordActivity::class.java)
			}
			//退出登录
			R.id.layout_userinfo_logout->{
				confirmDialog.openDialog("确定退出登录吗？")
			}
		}
	}

	override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
		super.onActivityResult(requestCode, resultCode, data)
		imageService.onActivityResult(requestCode, resultCode, data)
	}


	/**初始化用户信息*/
	private fun initUserInfo(){
		val user = SecurityUtil.getPrincipal()
		if(user != null){
			//设置头像
			imageService.parseUserImage(riv_userinfo_pic)
			//用户名
			et_userinfo_name.setText(user.name)
			//邮箱
			et_userinfo_email.setText(user.email)
			//手机号
			et_userinfo_phone.setText(user.phone)
		}
	}

	/**保存前的用户对象*/
	var currentUser: SysUser? = null

	/**调用接口保存用户信息*/
	private fun saveUserInfo(){
		currentUser = SecurityUtil.getPrincipal()
		if(currentUser == null){
			ToastUtils.toast("请先登录！")
			return
		}
		try {//校验信息
			val name = et_userinfo_name.text.toString()
			val email = et_userinfo_email.text.toString()
			val phone = et_userinfo_phone.text.toString()

			ValidateUtil.validateNotEmpty(name, "用户昵称")
			ValidateUtil.validateEmail(email, "电子邮箱")
			ValidateUtil.validatePhone(phone, "手机号码")

			currentUser!!.name = name
			currentUser!!.email = email
			currentUser!!.phone = phone

			//如果不为空,说明用户选择了头像, 需要上传新头像
			if(userSelectPhoto != null){
				//开始上传图片
				ToastUtils.toast("开始上传图片")
				val fileName = CommUtil.getUserHeaderImageName()
				val imageFile = imageService.saveBitmap(userSelectPhoto!!, fileName!!)
				//上传图片,上传之后再保存用户信息
				if(imageFile != null){
					imageService.getFileService().uploadImageFile(imageFile)
				}else{
					throw RuntimeException("保存图片失败！本地图片获取结果为空！")
				}
			}else{
				//没有上传图片,直接保存
				authManager.updateUserInfo(currentUser!!)
			}
		} catch (e: Exception) {
			ToastUtils.toast(e.message)
		}
	}

	/**处理http请求响应结果*/
	override fun handleResult(result: ApiResult, code: Int) {
		when(code){
			Constant.HTTP_KEY_UPDATE_USERINFO->{
				ToastUtils.toast("保存成功！")
				val user = result.getData() as SysUser
				SecurityUtil.setPrincipal(user)
			}
		}
	}


	/**用户选择的头像,如果选择了,表示需要上传,为空则直接保存,不上传图片*/
	private var userSelectPhoto: Bitmap? = null

	/**消息处理*/
	override fun handleMessage(msg: Message) {
		when(msg.what){
			//选择图片完成
			Constant.handler_event_selected_image->{
				//用户选择了图片,进行保存
				userSelectPhoto = msg.obj as Bitmap
				if(userSelectPhoto != null){
					//图片过大的话，需要对bitmap进行缩放处理
					val wh = Constant.IMAGE_HEADER_W_H_LIMIT
					if(userSelectPhoto!!.width > wh){
						userSelectPhoto = ImageUtil.imageCompress(userSelectPhoto!!, wh, wh)
					}
					
					//设置头像
					val drawable = BitmapDrawable(resources, userSelectPhoto)
					riv_userinfo_pic.setImageDrawable(drawable)
				}
			}
			//文件上传完毕
			Constant.handler_event_upload_file_finish->{
				ToastUtils.toast("文件上传完成")
				//保存图片之后,保存用户信息
				val sysFile = msg.obj as SysFile
				if(sysFile.id == null || sysFile.id == 0L){
					ToastUtils.toast("文件上传失败!")
					return
				}
				//设置文件id
				currentUser!!.imageId = sysFile.id

				//上传图片之后，保存用户
				authManager.updateUserInfo(currentUser!!)
			}
		}
	}

}